import Vue from 'vue'
import { login, logout } from '@/api/login'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  CACHE_INCLUDED_ROUTES,
  REFRESHTOKEN,
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { queryPermissionsByUser, handelRefreshToken } from '@/api/api'
import { getAction } from '@/api/manage'
import { getAllDict } from '../../api/api'

import store from '@/store'

const user = {
  state: {
    token: '',
    refreshToken: '',
    username: '',
    realname: '',
    tenantid: '',
    isPoliceAgencyId: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {},
    industryInformationId: '',
    // 系统安全模式
    sysSafeMode: null,
  },

  mutations: {
    SET_REFRESHTOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    },
    is_PoliceAgencyId: (state, records) => {
      state.isPoliceAgencyId = records
    },
    SET_industryInformationId: (state, records) => {
      state.industryInformationId = records
    },
    SET_SYS_SAFE_MODE: (state, sysSafeMode) => {
      if (typeof sysSafeMode === 'boolean') {
        state.sysSafeMode = sysSafeMode
      } else {
        state.sysSafeMode = false
      }
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(async (response) => {
            if (response.code == 200) {
              const result = response.result
              const userInfo = {
                ...result.userInfo,
                role: result.role,
              }
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(REFRESHTOKEN, result.refreshToken, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              // 再获取一下所有的字典值，将其存起来
              try {
                let dictDataRes = await getAllDict()
                if (dictDataRes.code == 200) {
                  Vue.ls.set(UI_CACHE_DB_DICT_DATA, dictDataRes.result)
                }
                commit('SET_TOKEN', result.token)
                commit('SET_REFRESHTOKEN', result.refreshToken)
                commit('SET_INFO', userInfo)
                commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
                commit('SET_AVATAR', userInfo.avatar)
              } catch (error) {}
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser()
          .then((response) => {
            let menuData = response.result.menu
            // 看是不是人文关怀页面
            if (store.state.user.info.role === 'love_and_care') {
              let humanisticConcernList = menuData.filter((item) => {
                return item.meta.title === '人文关怀'
              })
              menuData = humanisticConcernList[0].children
            }
            console.log(store.state.user.info.role, 'ksdfjkds', menuData)
            if (store.state.user.info.role === 'key_care') {
              let careFamilyList = menuData.filter((item) => {
                //return item.meta.title === '重点关爱+'
                return item.name == 'careFamily'
              })
              console.log(careFamilyList, 'careFamilyList')
              menuData = careFamilyList[0].children
            }
            const authData = response.result.auth
            const allAuthData = response.result.allAuth
            //Vue.ls.set(USER_AUTH,authData);
            sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
            sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
            if (menuData && menuData.length > 0) {
              // //update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              // menuData.forEach((item, index) => {
              //   if (item["children"]) {
              //     let hasChildrenMenu = item["children"].filter((i) => {
              //       return !i.hidden || i.hidden == false
              //     })
              //     if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
              //       item["hidden"] = true
              //     }
              //   }
              // })
              // //console.log(" menu show json ", menuData)
              // //update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              commit('SET_PERMISSIONLIST', menuData)
              // 设置系统安全模式
              commit('SET_SYS_SAFE_MODE', response.result.sysSafeMode)
            } else {
              reject('getPermissionList: permissions must be a non-null array !')
            }
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 刷新token
    getRefreshToken({ commit, state }) {
      return new Promise((resolve, reject) => {
        let refreshToken = state.refreshToken || Vue.ls.get(REFRESHTOKEN)
        handelRefreshToken({ refreshToken })
          .then(async (res) => {
            const result = res.result
            const userInfo = {
              ...result.userInfo,
              role: result.role,
            }
            Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(REFRESHTOKEN, result.refreshToken, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
            try {
              let dictDataRes = await getAllDict()
              if (dictDataRes.code == 200) {
                Vue.ls.set(UI_CACHE_DB_DICT_DATA, dictDataRes.result)
              }
            } catch (error) {}
            commit('SET_TOKEN', result.token)
            commit('SET_REFRESHTOKEN', result.refreshToken)
            commit('SET_INFO', userInfo)
            commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
            commit('SET_AVATAR', userInfo.avatar)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        Vue.ls.remove(TENANT_ID)
        Vue.ls.remove(REFRESHTOKEN)
        //console.log('logoutToken: '+ logoutToken)
        logout(logoutToken)
          .then(() => {
            if (process.env.VUE_APP_SSO == 'true') {
              let sevice = 'http://' + window.location.host + '/'
              let serviceUrl = encodeURIComponent(sevice)
              window.location.href = serviceUrl + '/logout'
            }
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },

    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      commit('SET_TENANT', id)
    },
  },
}

export default user
